package cn.example.uibestpracticetest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<>();

    private EditText inputText;

    private Button send;

    private RecyclerView recyclerView;

    private MsgAdapter msgAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initMsgList();

        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);


        recyclerView = findViewById(R.id.msg_recycle_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        MsgAdapter msgAdapter = new MsgAdapter(msgList);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if(!"".equals(content)){
                    Msg msg = new Msg(content, Msg.TYPE_SENT);
                    msgList.add(msg);
                    msgAdapter.notifyItemInserted(msgList.size() - 1);
                    recyclerView.scrollToPosition((msgList.size() - 1));
                    inputText.setText("");
                }
            }
        });
        recyclerView.setAdapter(msgAdapter);
    }

    public void initMsgList(){
        msgList.add(new Msg("Hi! I am Frank!", 0));
        msgList.add(new Msg("Hello, Frank! I am Jack. How are you?", 1));
        msgList.add(new Msg("I am fine, thanks.And you?", 0));
        msgList.add(new Msg("I am Ok.", 1));
    }
}